package com.hippo.core.ui.compose.login.forget

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hippo.core.R
import com.hippo.core.respository.ApiRepository
import com.hippo.core.state.DialogType
import com.hippo.core.state.ForgetState
import com.hippo.core.utils.UiHandler
import kotlinx.coroutines.launch

class ForgetVM :ViewModel(){

    var uiState by mutableStateOf(ForgetState())

    fun updateState(state: ForgetState){
        uiState = state
    }



    fun resetPassword(callback: (Boolean)->Unit){
        viewModelScope.launch {
            callback(true)
        }
    }

    fun dismissDialog() {
        uiState = uiState.copy(dialogType = DialogType.Idle)
    }

    fun showLoading() {
        uiState = uiState.copy(dialogType = DialogType.LoadingDialog())
    }

    fun sendEmailCode(callback: ()->Unit){

        if(uiState.email.isNullOrBlank()){
            UiHandler.showToast(R.string.login_2)
            return
        }

        showLoading()

        viewModelScope.launch {
            ApiRepository.sendEmailCode(uiState.email!!,"2")
                .onFailure {
                    dismissDialog()
                    UiHandler.showToast(it.msg)
                }
                .onSuccess {
                    dismissDialog()
                    callback()
                }
        }


    }


    fun chkEmailCode(verifyCode: String,callback: (Boolean)->Unit){
        showLoading()
        viewModelScope.launch {
            ApiRepository.chkEmailCode(verifyCode)
                .onFailure {
                    dismissDialog()
                    UiHandler.showToast(it.msg)
                }
                .onSuccess {
                    dismissDialog()
                    callback(true)
                }
        }

    }



}